package com.wyk.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.wyk.bean.Payment;
import com.wyk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.sql.ResultSet;

/**
 * @author WangYuKai
 * @Date 2022/8/1
 * @apiNote
 */
@RestController
@Slf4j
public class CircleBreakController {
    //注入模板
    @Autowired
    private RestTemplate restTemplate;

    //调用微服务地址
    public static final String SERVER_URI = "http://nacos-payment-provider";

    @GetMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback")
    //@SentinelResource(value = "fallback",fallback = "handlerFallback")
    //@SentinelResource(value = "fallback",blockHandler = "blockHanlder")
    @SentinelResource(value = "fallback",blockHandler = "blockHanlder",fallback ="handlerFallback" )
    public Result fallback(@PathVariable("id")Long id){
        Result result = restTemplate.getForObject(SERVER_URI + "/paymentSQL/" + id, Result.class, id);
        if(id == 4){
            throw new IllegalArgumentException("参数异常");
        }else if(result.getData() == null){
            throw new NullPointerException("空指针错误");
        }
        return result;
    }
    public Result handlerFallback(@PathVariable("id") Long id){
        Payment payment = new Payment(id, null);
        return new Result(444,"兜底的解决方案",payment);
    }

    public Result blockHanlder(@PathVariable("id") Long id, BlockException e){
        Payment payment = new Payment(id, null);
        return new Result(444,"block兜底的解决方案",payment);
    }
}
